<template>
  <div class="books-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>图书管理</span>
          <el-button type="primary" @click="handleAdd">添加图书</el-button>
        </div>
      </template>
      
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="搜索图书..."
          class="search-input"
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      
      <el-table
        :data="filteredBooks"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="书名" />
        <el-table-column prop="author" label="作者" />
        <el-table-column prop="publisher" label="出版社" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === '可借阅' ? 'success' : 'danger'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button
              size="small"
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 添加/编辑图书对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加图书' : '编辑图书'"
      width="500px"
    >
      <el-form
        :model="bookForm"
        :rules="rules"
        ref="bookFormRef"
        label-width="80px"
      >
        <el-form-item label="书名" prop="title">
          <el-input v-model="bookForm.title" />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="bookForm.author" />
        </el-form-item>
        <el-form-item label="出版社" prop="publisher">
          <el-input v-model="bookForm.publisher" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { useBookStore } from '../stores/bookStore'
import { ElMessage, ElMessageBox } from 'element-plus'

const bookStore = useBookStore()
const loading = ref(false)
const searchQuery = ref('')
const dialogVisible = ref(false)
const dialogType = ref('add')
const bookFormRef = ref(null)
const bookForm = ref({
  id: '',
  title: '',
  author: '',
  publisher: '',
  status: '可借阅'
})

const rules = {
  title: [{ required: true, message: '请输入书名', trigger: 'blur' }],
  author: [{ required: true, message: '请输入作者', trigger: 'blur' }],
  publisher: [{ required: true, message: '请输入出版社', trigger: 'blur' }]
}

const filteredBooks = computed(() => {
  if (!searchQuery.value) return bookStore.books
  const query = searchQuery.value.toLowerCase()
  return bookStore.books.filter(book => 
    book.title.toLowerCase().includes(query) ||
    book.author.toLowerCase().includes(query) ||
    book.publisher.toLowerCase().includes(query)
  )
})

const handleSearch = () => {
  // 搜索逻辑已经在 computed 中实现
}

const handleAdd = () => {
  dialogType.value = 'add'
  bookForm.value = {
    id: '',
    title: '',
    author: '',
    publisher: '',
    status: '可借阅'
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  bookForm.value = { ...row }
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除这本书吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    bookStore.books = bookStore.books.filter(book => book.id !== row.id)
    ElMessage.success('删除成功')
  }).catch(() => {})
}

const handleSubmit = async () => {
  if (!bookFormRef.value) return
  
  await bookFormRef.value.validate(async (valid) => {
    if (valid) {
      if (dialogType.value === 'add') {
        const newId = Math.max(...bookStore.books.map(book => book.id), 0) + 1
        bookStore.books.push({
          ...bookForm.value,
          id: newId
        })
        ElMessage.success('添加成功')
      } else {
        const index = bookStore.books.findIndex(book => book.id === bookForm.value.id)
        if (index !== -1) {
          bookStore.books[index] = { ...bookForm.value }
        }
        ElMessage.success('编辑成功')
      }
      dialogVisible.value = false
    }
  })
}

onMounted(async () => {
  loading.value = true
  await bookStore.fetchBooks()
  loading.value = false
})
</script>

<style scoped>
.books-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-bar {
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}
</style> 